/**
 * 将颜色转换为hover效果颜色
 * @param {string} color - 原始颜色，可以是十六进制、rgb或rgba格式
 * @param {number} percent - 亮度调整百分比，正值为调亮，负值为调暗，默认10
 * @returns {string} 调整后的颜色，保持原格式
 */
function getHoverColor(color, percent = 10) {
	// 解析十六进制颜色
	if (color.startsWith('#')) {
		return hexToHover(color, percent);
	}
	// 解析rgb或rgba颜色
	else if (color.startsWith('rgb')) {
		return rgbToHover(color, percent);
	}
	// 不支持的颜色格式
	return color;
}

/**
 * 处理十六进制颜色
 */
function hexToHover(hex, percent) {
	// 移除#号
	hex = hex.replace('#', '');
	// 解析RGB值
	let r = parseInt(hex.substring(0, 2), 16);
	let g = parseInt(hex.substring(2, 4), 16);
	let b = parseInt(hex.substring(4, 6), 16);
	let a = hex.length === 8 ? parseInt(hex.substring(6, 8), 16) / 255 : 1;
	// 调整亮度
	[r, g, b] = adjustBrightness(r, g, b, percent);
	// 转换回十六进制
	let newHex = `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
	// 添加alpha通道（如果有）
	if (hex.length === 8) {
		newHex += Math.round(a * 255).toString(16).padStart(2, '0');
	}
	return newHex;
}

/**
 * 处理rgb或rgba颜色
 */
function rgbToHover(rgb, percent) {
	// 提取rgba值
	const match = rgb.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
	if (!match) return rgb;
	let r = parseInt(match[1]);
	let g = parseInt(match[2]);
	let b = parseInt(match[3]);
	let a = match[4] ? parseFloat(match[4]) : 1;
	// 调整亮度
	[r, g, b] = adjustBrightness(r, g, b, percent);
	// 构建新的rgb/rgba字符串
	return match[4] ? `rgba(${r}, ${g}, ${b}, ${a})` : `rgb(${r}, ${g}, ${b})`;
}

/**
 * 调整颜色亮度
 */
function adjustBrightness(r, g, b, percent) {
	// 转换为HSV颜色空间以更好地调整亮度
	const hsv = rgbToHsv(r, g, b);
	// 调整亮度 (value)
	hsv.v = Math.max(0, Math.min(100, hsv.v + percent));
	// 转换回RGB
	return hsvToRgb(hsv.h, hsv.s, hsv.v);
}

/**
 * RGB转HSV
 */
function rgbToHsv(r, g, b) {
	r /= 255;
	g /= 255;
	b /= 255;
	const max = Math.max(r, g, b);
	const min = Math.min(r, g, b);
	let h, s, v = max;
	const d = max - min;
	s = max === 0 ? 0 : d / max;
	if (max === min) {
		h = 0; // 灰色
	} else {
		switch (max) {
			case r:
				h = (g - b) / d + (g < b ? 6 : 0);
				break;
			case g:
				h = (b - r) / d + 2;
				break;
			case b:
				h = (r - g) / d + 4;
				break;
		}
		h *= 60;
	}
	return { h, s: s * 100, v: v * 100 };
}

/**
 * HSV转RGB
 */
function hsvToRgb(h, s, v) {
	s /= 100;
	v /= 100;
	let r, g, b;
	const i = Math.floor(h / 60);
	const f = h / 60 - i;
	const p = v * (1 - s);
	const q = v * (1 - f * s);
	const t = v * (1 - (1 - f) * s);
	switch (i % 6) {
		case 0:
			r = v, g = t, b = p;
			break;
		case 1:
			r = q, g = v, b = p;
			break;
		case 2:
			r = p, g = v, b = t;
			break;
		case 3:
			r = p, g = q, b = v;
			break;
		case 4:
			r = t, g = p, b = v;
			break;
		case 5:
			r = v, g = p, b = q;
			break;
	}
	return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}

export default getHoverColor;